#import "SimMulImagePickerVC.h"
#import "SimAlbumsListVC.h"
#import "SimAssetsCollectionVC.h"

@interface SimMulImagePickerVC ()

@property (nonatomic, strong) SimAlbumsListVC *albumsViewController;

@end

@implementation SimMulImagePickerVC

+ (BOOL)isAccessible
{
    return ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary] &&
            [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]);
}

- (instancetype)init
{
    self = [super init];
    
    if (self) {
        _groupTypes = @[@(ALAssetsGroupSavedPhotos),
//                            @(ALAssetsGroupPhotoStream),
                            @(ALAssetsGroupAlbum)
                            ];
        _filterType = SimImagePickerFilterTypeNone;
        _minimumNumberOfSelection = 1;
        _numberOfColumnsInPortrait = 4;
        _numberOfColumnsInLandscape = 7;
        
        _assetsLibrary = [ALAssetsLibrary new];
        _selectedAssets = [NSMutableArray array];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(assetsLibraryChanged:)
                                                     name:ALAssetsLibraryChangedNotification
                                                   object:nil];

        _albumsViewController = [[SimAlbumsListVC alloc] init];
        _albumsViewController.imagePicker = self;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:_albumsViewController];
        [self addChildViewController:navigationController];
        navigationController.view.frame = self.view.bounds;
        [self.view addSubview:navigationController.view];
        [navigationController didMoveToParentViewController:self];

        
        [self updateAssetsGroupsWithCompletion:^{
            if (self.groupTypes.count > 0) {
                [_albumsViewController.tableView reloadData];
                SimAssetsCollectionVC *assetsViewController = [[SimAssetsCollectionVC alloc] init];
                assetsViewController.imagePicker = self;
                assetsViewController.assetsGroup = self.assetsGroups[0];
                [_albumsViewController.navigationController pushViewController:assetsViewController animated:NO];
            }
        }];
    }
    
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)updateAssetsGroupsWithCompletion:(void (^)(void))completion
{
    [self fetchAssetsGroupsWithTypes:self.groupTypes completion:^(NSArray *assetsGroups) {
        NSMutableDictionary *mappedAssetsGroups = [NSMutableDictionary dictionaryWithCapacity:assetsGroups.count];
        for (ALAssetsGroup *assetsGroup in assetsGroups) {
            id groupType = [assetsGroup valueForProperty:ALAssetsGroupPropertyType];
            NSMutableArray *array = mappedAssetsGroups[groupType];
            if (!array) {
                array = [NSMutableArray array];
                mappedAssetsGroups[groupType] = array;
            }
            
            [array addObject:assetsGroup];
        }
        
        NSMutableArray *sortedAssetsGroups = [NSMutableArray arrayWithCapacity:self.groupTypes.count];
        for (NSValue *groupType in self.groupTypes) {
            NSArray *array = mappedAssetsGroups[groupType];
            if (array) {
                [sortedAssetsGroups addObjectsFromArray:array];
            }
        }
        
        _assetsGroups = sortedAssetsGroups;
        if (completion) {
            completion();
        }
    }];
}

- (void)fetchAssetsGroupsWithTypes:(NSArray *)types completion:(void (^)(NSArray *assetsGroups))completion
{
    __block NSMutableArray *assetsGroups = [NSMutableArray array];
    __block NSUInteger numberOfFinishedTypes = 0;
    
    ALAssetsLibrary *assetsLibrary = self.assetsLibrary;
    ALAssetsFilter *assetsFilter;
    
    switch (self.filterType) {
        case SimImagePickerFilterTypeNone:
            assetsFilter = [ALAssetsFilter allAssets];
            break;
            
        case SimImagePickerFilterTypePhotos:
            assetsFilter = [ALAssetsFilter allPhotos];
            break;
            
        case SimImagePickerFilterTypeVideos:
            assetsFilter = [ALAssetsFilter allVideos];
            break;
    }
    
    for (NSNumber *type in types) {
        [assetsLibrary enumerateGroupsWithTypes:[type unsignedIntegerValue]
                                     usingBlock:^(ALAssetsGroup *assetsGroup, BOOL *stop) {
                                         if (assetsGroup) {
                                             // Apply assets filter
                                             [assetsGroup setAssetsFilter:assetsFilter];
                                             
                                             // Add assets group
                                             [assetsGroups addObject:assetsGroup];
                                         } else {
                                             numberOfFinishedTypes++;
                                         }
                                         
                                         // Check if the loading finished
                                         if (numberOfFinishedTypes == types.count) {
                                             if (completion) {
                                                 completion(assetsGroups);
                                             }
                                         }
                                     } failureBlock:^(NSError *error) {
                                         NSLog(@"Error: %@", [error localizedDescription]);
                                     }];
    }
}

#pragma mark - Handling Assets Library Changes
- (void)assetsLibraryChanged:(NSNotification *)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateAssetsGroupsWithCompletion:^{
            [self.albumsViewController.tableView reloadData];
        }];
    });
}


@end
